package dancrawler.client;

import dancrawler.server.Gameserver;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 */
public class StartWindow1 extends JFrame implements ActionListener, WindowListener {

  private Gameserver gs = null;
  private Client client;
  private Image icon = null;
  private StartPanel sp = new StartPanel();
  private Installer i = new Installer();

  private class StartPanel extends JPanel {

    private JButton bDirect = new JButton("START");
    private JButton bStart = new JButton("START");
    private JComboBox character = new JComboBox();
    private JTextField pname = new JTextField(20);
    private JTextField address = new JTextField(20);
    private JTextField port = new JTextField(20);

    public StartPanel() {
      setLayout(new GridLayout(7, 2));
      add(new JLabel(), BorderLayout.NORTH);
      add(new JLabel(), BorderLayout.NORTH);
      add(new JLabel("Nickname:   ", JLabel.RIGHT));
      add(pname);/* // Next version
       add(new JLabel("Character:   ", JLabel.RIGHT));
       add(character); */
      add(new JLabel("Address:   ", JLabel.RIGHT));
      add(address);
      add(new JLabel("Port:   ", JLabel.RIGHT));
      add(port);
      add(new JLabel("OK    ", JLabel.RIGHT));
      add(bStart);
      pack();
    }
  }

  public StartWindow1(Client client) throws UnsupportedEncodingException {
    super();
    if (i.PathExists() != null) {
      JOptionPane.showMessageDialog(this, i.PathExists());
    }
    if (i.makeDataFolder() != null) {
      JOptionPane.showMessageDialog(this, i.makeDataFolder());
    } else {
      try {
        i.copyFiles();
      } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(this, "Cannot find files: " + ex);
      } catch (IOException ex) {
        JOptionPane.showMessageDialog(this, "IO Error: " + ex);
      }
      try {
        i.copyMusic();
      } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(this, "Cannot find files: " + ex);
      } catch (IOException ex) {
        JOptionPane.showMessageDialog(this, "IO Error: " + ex);
      }

    }
    i = null;

    // Sets size and centers
    setLocationRelativeTo(
            null);
    this.setSize(
            326, 300);
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    int w = this.getSize().width;
    int h = this.getSize().height;
    int x = (dim.width - w) / 2;
    int y = (dim.height - h) / 2;

    this.add(sp, BorderLayout.CENTER);
    // Loads and add image as icon

    this.setLocation(x, y);


    try {
      Image icon = ImageIO.read(Main.class.getResource("/res/img/danborgeDW.png"));
    } catch (IOException ex) {
    }

    // IP and port information
    try {
      this.sp.address.setText(InetAddress.getLocalHost().toString().split("/")[1]);
    } catch (UnknownHostException ex) {
    }
    this.sp.port.setText(
            "1881");
    this.sp.pname.setText(
            "Enter Nick");

    this.setIconImage(icon);

    this.setTitle(
            "DanCrawler Launcher version 1.0 - "
            + "by Team 4 - Dan Børge | Kittelsen, "
            + "Gjevik, Jakobsen");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    this.sp.bDirect.addActionListener(
            this);
    this.sp.bDirect.setAlignmentX(Component.CENTER_ALIGNMENT);

    this.sp.bStart.addActionListener(
            this);
    this.sp.bStart.setAlignmentX(Component.CENTER_ALIGNMENT);

    pack();
  }

  private void connect(InetSocketAddress addr) throws IOException {
    if (this.sp.pname.getText().isEmpty()) {
      return;
    }
    System.out.println(addr.toString() + addr.getHostString() + addr.getPort());
    client = new Client(this.sp.pname.getText());
    MainWindow mw = new MainWindow(client);
    client.addGameListener(mw);
    client.connect(addr.getHostString(), addr.getPort());
    mw.addWindowListener(this);
    mw.setLocationRelativeTo(this);
    mw.setVisible(true);
    mw.setBackground(Color.black);
    this.setVisible(false);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == this.sp.bStart) {
      String sAddr = this.sp.address.getText().toString().trim();
      String lAddr = null;
      int port = Integer.parseInt(this.sp.port.getText());
      try {
        lAddr = InetAddress.getLocalHost().toString().split("/")[1].toString().trim();
      } catch (UnknownHostException ex) {
      }
      System.out.println(sAddr);
      if (sAddr != null) {
      }
      if (sAddr.equals(lAddr)) {
        System.out.println("Server");
        try {
          gs = new Gameserver();
          gs.start();
          connect(new InetSocketAddress("localhost", 1881));
        } catch (IOException ex) {
        }
      } else if (sAddr != null) {
        System.out.println("Client");
        try {
          connect(new InetSocketAddress(sAddr, port));
        } catch (IOException ex) {
          System.out.println(ex);
          JOptionPane.showMessageDialog(this, "Could not connect!");
        }
      } else {
        System.out.println("Wat");
      }
    }
  }

  @Override
  public void windowOpened(WindowEvent e) {
  }

  @Override
  public void windowClosing(WindowEvent e) {
  }

  @Override
  public void windowClosed(WindowEvent e) {
    this.setVisible(true);
    if (client != null) {
      client.stopClient();
    }
    if (gs != null) {
      gs.stop();
      gs = null;
    }
  }

  @Override
  public void windowIconified(WindowEvent e) {
  }

  @Override
  public void windowDeiconified(WindowEvent e) {
  }

  @Override
  public void windowActivated(WindowEvent e) {
  }

  @Override
  public void windowDeactivated(WindowEvent e) {
  }
}
